package cn.itcast.CompletableFuture;

import com.google.common.util.concurrent.*;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;
/**
 * @Author : 叶荻风
 * @create : 2024/8/9 17:08
 */
public class Future {
    public static void main(String[] args) {
        //假设3个任务，任务1和2完成后，执行任务3
        ExecutorService executor = Executors.newFixedThreadPool(5);
        ListeningExecutorService guavaExecutor = MoreExecutors.listeningDecorator(executor);
        //提交两个任务
        ListenableFuture<String> future1 = guavaExecutor.submit(() -> {
            //step 1

            System.out.println("执行step 1");
            Thread.sleep(5000);
            return "step1 result";
        });
        ListenableFuture<String> future2 = guavaExecutor.submit(() -> {
            //step 2
            System.out.println("执行step 2");
            Thread.sleep(5000);
            return "step2 result";
        });
        ListenableFuture<List<String>> future1And2 = Futures.allAsList(future1, future2);

        //纯future,编排任务是嵌套式的，任务复杂了很难读扇
        Futures.addCallback(future1And2, new FutureCallback<List<String>>() {
            @Override
            public void onSuccess(List<String> strings) {
                System.out.println(strings);
                ListenableFuture<String> future3 = guavaExecutor.submit(() -> {
                    System.out.println("执行step 3");
                    return "step3 result";
                });
                Futures.addCallback(future3, new FutureCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        System.out.println(s);
                    }
                    @Override
                    public void onFailure(Throwable throwable) {

                    }
                });
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        },guavaExecutor);



    }
}
